package com.lw.leetcode.arr.a;

import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * arr
 * 989. 数组形式的整数加法
 *
 * @author liw
 * @version 1.0
 * @date 2021/10/28 14:48
 */
public class AddToArrayForm {

    public static void main(String[] args) {
        AddToArrayForm test = new AddToArrayForm();
        int[] arr = {1,2,3,4,5};
        int k = 123;
        List<Integer> list = test.addToArrayForm(arr, k);

        System.out.println(list);
    }


    public List<Integer> addToArrayForm(int[] num, int k) {
        int length = num.length;
        int c = 0;
        for (int i = length - 1; i >= 0; i--) {
            int a = num[i];
            int b = k % 10;
            k /= 10;
            int v = a + b + c;
            if (v > 9) {
                num[i] = v - 10;
                c = 1;
            } else {
                num[i] = v;
                c = 0;
            }
        }
        List<Integer> list;
        if (k == 0) {
            if (c == 0) {
                list = new ArrayList<>(length);
            } else {
                list = new ArrayList<>(length + 1);
                list.add(1);
            }
        } else {
            k += c;
            char[] chars = String.valueOf(k).toCharArray();
            list = new ArrayList<>(length + chars.length);
            for (char aChar : chars) {
                list.add(aChar - '0');
            }
        }
        for (int i : num) {
            list.add(i);
        }
        return list;
    }

}
